<template>
  <a-modal :title="title" v-model="show" :maskClosable="false" :width="1050" placement="right" :closable="true"
    @cancel="onClose" :footer="null" :visiable="clearPlanMapOperationVisiable">
    <div>
      <a-tabs v-model="activeKey">
        <a-tab-pane key="1" tab="清分清算方案确定" :disabled="activeKey == '2'">
          <a-form :form="form">
            <a-row>
              <a-col :md="12" :sm="24">
                <a-form-item label="清分清算方案标识" v-bind="formItemLayout">
                  <a-input v-decorator="['clearPlanId']" placeholder="系统自动生成" :disabled="true" />
                </a-form-item>
                <a-form-item label="id" v-bind="formItemLayout" style="display: none">
                  <a-input v-decorator="['id']" />
                </a-form-item>
              </a-col>
              <a-col :md="12" :sm="24">
                <a-form-item label="方案确定描述" v-bind="formItemLayout">
                  <a-input v-decorator="['planMapDesc', { rules: [{ validator: planMapDescValidator }] }]"
                    :disabled="true" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :md="12" :sm="24">
                <a-form-item label="机构标识" v-bind="formItemLayout">
                  <a-input v-decorator="['instId', { rules: [{ required: true, message: '必填' }] }]" :disabled="true" />
                </a-form-item>
              </a-col>
              <a-col :md="12" :sm="24">
                <a-form-item label="渠道标识列表" v-bind="formItemLayout">
                  <a-select mode="default" :allowClear="true" style="width: 100%" show-search placeholder="请选择"
                    option-filter-prop="children" :filter-option="filterOption" :disabled="this.isUpd"
                    @focus="selectTransChannelIdList"
                    v-decorator="['transChannelIdList', { rules: [{ required: true, message: '必填' }] }]">
                    <a-select-option v-for="(d, index) in transChannelIdListData" :key="d.paramKey">
                      {{ d.paramDesc }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :md="12" :sm="24">
                <a-form-item label="通道标识列表" v-bind="formItemLayout">
                  <a-select mode="default" :allowClear="true" style="width: 100%" show-search placeholder="请选择"
                    option-filter-prop="children" :filter-option="filterOption" :disabled="this.isUpd"
                    @focus="selectPayChannelIdList"
                    v-decorator="['payChannelIdList', { rules: [{ required: true, message: '必填' }] }]">
                    <a-select-option v-for="(d, index) in payChannelIdListData" :key="d.paramKey">
                      {{ d.paramDesc }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="12" :sm="24">
                <a-form-item label="交易码" v-bind="formItemLayout">
                  <a-select mode="default" :allowClear="true" style="width: 100%" show-search placeholder="请选择"
                    option-filter-prop="children" :filter-option="filterOption" :disabled="this.isUpd"
                    @focus="selectTxnNum" v-decorator="['txnNum', { rules: [{ required: true, message: '必填' }] }]">
                    <a-select-option v-for="(d, index) in txnNumData" :key="d.txnNum">
                      {{ d.txnDesc }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :md="12" :sm="24">
                <a-form-item label="业务类型" v-bind="formItemLayout">
                  <a-select mode="default" :allowClear="true" style="width: 100%" show-search placeholder="请选择"
                    option-filter-prop="children" :filter-option="filterOption" :disabled="this.isUpd"
                    @focus="selectCsmcBizTypeList"
                    v-decorator="['csmcBizTypeList', { rules: [{ required: true, message: '必填' }] }]">
                    <a-select-option v-for="(d, index) in csmcBizTypeListData" :key="d.paramKey">
                      {{ d.paramDesc }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="12" :sm="24">
                <a-form-item label="对账结果" v-bind="formItemLayout">
                  <a-select mode="default" :allowClear="true" style="width: 100%" show-search placeholder="请选择"
                    option-filter-prop="children" :filter-option="filterOption" :disabled="this.isUpd"
                    @focus="selectReconRslt"
                    v-decorator="['reconRslt', { rules: [{ required: true, message: '必填' }] }]">
                    <a-select-option v-for="(d, index) in reconRsltData" :key="d.paramKey">
                      {{ d.paramDesc }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :md="12" :sm="24">
                <a-form-item label="支付账号类型" v-bind="formItemLayout">
                  <a-select mode="default" :allowClear="true" style="width: 100%" show-search placeholder="请选择"
                    option-filter-prop="children" :filter-option="filterOption" :disabled="this.isUpd"
                    @focus="selectPayAcctType"
                    v-decorator="['payAcctType', { rules: [{ required: true, message: '必填' }] }]">
                    <a-select-option v-for="(d, index) in payAcctTypeData" :key="d.paramKey">
                      {{ d.paramDesc }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="12" :sm="24">
                <a-form-item label="其他匹配条件1" v-bind="formItemLayout">
                  <a-input v-decorator="['otherCond1']" :disabled="this.isUpd" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :md="12" :sm="24">
                <a-form-item label="其他匹配条件2" v-bind="formItemLayout">
                  <a-input v-decorator="['otherCond2', { rules: [{ required: true, message: '必填' }] }]"
                    :disabled="this.isUpd" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :md="12" :sm="24" v-show="this.isStop == true">
                <a-form-item label="停用原因" v-bind="formItemLayout">
                  <a-input v-decorator="['stopReason', { rules: [{ required: this.isStop, message: '必填' }] }]" />
                </a-form-item>
              </a-col>

              <a-col :md="12" :sm="24" v-show="this.isCancel == true">
                <a-form-item label="注销原因" v-bind="formItemLayout">
                  <a-input v-decorator="['cancelReason', { rules: [{ required: this.isCancel, message: '必填' }] }]" />
                </a-form-item>
              </a-col>
            </a-row>
            <div style="text-align: center">
              <a-button style="width: 128px" @click="handleSubmit" type="btn-next" :loading="loading">下一步</a-button>
              <a-button style="width: 128px" @click="onClose">关闭</a-button>
            </div>

          </a-form>
        </a-tab-pane>

        <!--会计分录-->
        <a-tab-pane key="2" tab="清分清算方案资金配置" :disabled="activeKey == '1'">
          <div>
            <div class="operator" v-show="this.title == '方案新增' || this.title == '方案修改'">
              <a-button ghost type="primary" @click="addClearPlan">新增</a-button>
            </div>
            <!-- 表格区域 -->
            <a-table ref="TableInfo" :columns="columns" :rowKey="record => record.id" :dataSource="dataSource"
              :pagination="pagination" :loading="loading" :scroll="{ x: 900 }" @change="handleTableChange">
              <template slot="email" slot-scope="text, record">
                <a-popover placement="topLeft">
                  <template slot="content">
                    <div>{{ text }}</div>
                  </template>
                  <p style="width: 150px;margin-bottom: 0">{{ text }}</p>
                </a-popover>
              </template>
              <template slot="acctEntryOperation" slot-scope="text, record, index">
                <a-icon type="setting" theme="twoTone" twoToneColor="#4a9ff5" @click="editClearPlan(record)" title="修改">
                </a-icon>&nbsp;
                <a-icon type="delete" theme="twoTone" twoToneColor="#42b983" @click="delClearPlan(record, index)"
                  title="删除"></a-icon>
              </template>
            </a-table>
          </div>

          <div style="text-align: center" v-show="this.title !== '方案详情'">
            <a-button style="width: 128px" @click="clearPlanSubmit" type="btn-next" :loading="loading">提交审批</a-button>
            <a-button style="width: 128px" @click="onClose">关闭</a-button>
          </div>

          <div>
            <clear-plan-basic ref="clearPlanBasic" @close="handleClearPlanBasicClose"
              @success="handleClearPlanBasicSuccess" :clearPlanBasicVisiable="clearPlanBasic.visiable">
            </clear-plan-basic>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>

  </a-modal>
</template>
<script>

import ClearPlanBasic from "./ClearPlanBasic";
import Form from "../../../../system/form/Form";

const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 }
}
export default {
  name: 'ClearPlanMapOperation',
  components: { Form, ClearPlanBasic },
  comments: { ClearPlanBasic },
  props: {
    clearPlanMapOperationVisiable: {
      default: false
    },
    instId: '',
  },
  data() {
    return {
      activeKey: '1',
      title: '方案新增',
      isStop: false,
      isCancel: false,
      isUpd: false,
      isView: true,
      loading: false,
      formItemLayout,
      form: this.$form.createForm(this),
      validateStatus: '',

      clearPlanBasic: {
        visiable: false,
      },
      queryParams: {
        instId: '',
        clearPlanId: '',
      },
      info: {},
      optFlagTmp: '',

      tmpData: {},

      transChannelIdListData: [],
      payChannelIdListData: [],
      csmcBizTypeListData: [],
      txnNumData: [],
      reconRsltData: [],
      payAcctTypeData: [],

      dataSource: [],
      paginationInfo: null,
      pagination: {
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
    }
  },
  computed: {
    show: {
      get: function () {
        return this.clearPlanMapOperationVisiable
      },
      set: function () {
      }
    },
    columns() {
      return [{
        title: '清分次序',
        dataIndex: 'clearSeq',
        scopedSlots: { customRender: 'clearSeq' },
      }, {
        title: '清算资金类型',
        dataIndex: 'settleFundType',
        customRender: (text, row, index) => {
          switch (text) {
            case '00':
              return '交易金额'
            case '01':
              return '商户手续费'
            case '02':
              return '商户入账净额'
            case '03':
              return '商户优惠手续费'
            case '04':
              return '代理商手续费'
            case '10':
              return '银联转接清算费'
            case '11':
              return '银联交换费(卡组织手续费）'
            case '12':
              return '品牌服务费'
            case '13':
              return '差错费用'
            case '14':
              return '支付通道手续费'
            case '20':
              return '收单手续费'
            case '21':
              return '发卡手续费'
            case '22':
              return '分行补贴手续费'
            case '30':
              return '跨行持卡人手续费'
            case '31':
              return '持卡人异地手续费'
            default:
              return text
          }
        }
      }, {
        title: '清分规则标识',
        dataIndex: 'clearRuleId',
        scopedSlots: { customRender: 'clearRuleId' },
      }, {
        title: '清算规则标识',
        dataIndex: 'settleRuleId',
        scopedSlots: { customRender: 'settleRuleId' },
      }, {
        title: '操作',
        dataIndex: 'acctEntryOperation',
        fixed: 'right',
        show: false,
        scopedSlots: { customRender: 'acctEntryOperation' }
      }]
    }
  },
  mounted() {

  },

  methods: {
    planMapDescValidator(rule, value, callback) {
      callback(value ? (/(^.{0,32}$)/.test(value) ? undefined : new Error('请注意输入长度')) : undefined)
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    selectTransChannelIdList() {
      this.transChannelIdListData = []
      let type = 'transChannelList'
      this.$get('/admin/csmc/sysParam', { type: type }).then((r) => {
        let result = r.data
        result.forEach(r => {
          this.transChannelIdListData.push(r);
        })
      })
    },

    selectPayChannelIdList() {
      this.payChannelIdListData = []
      let type = 'payChannelList'
      this.$get('/admin/csmc/sysParam', { type: type }).then((r) => {
        let result = r.data
        result.forEach(r => {
          this.payChannelIdListData.push(r);
        })
      })
    },
    selectTxnNum() {
      this.txnNumData = []
      this.$get('/admin/csmc/txncdConv').then((r) => {
        let result = r.data
        result.forEach(r => {
          this.txnNumData.push(r);
        })
      })
    },
    selectCsmcBizTypeList() {
      this.csmcBizTypeListData = []
      let type = 'bizProdList'
      this.$get('/admin/csmc/sysParam', { type: type }).then((r) => {
        let result = r.data
        result.forEach(r => {
          this.csmcBizTypeListData.push(r);
        })
      })
    },
    selectReconRslt() {
      this.reconRsltData = []
      let type = 'dzRsltList'
      this.$get('/admin/csmc/sysParam', { type: type }).then((r) => {
        let result = r.data
        result.forEach(r => {
          this.reconRsltData.push(r);
        })
      })
    },
    selectPayAcctType() {
      this.payAcctTypeData = []
      let type = 'payAcctList'
      this.$get('/admin/csmc/sysParam', { type: type }).then((r) => {
        let result = r.data
        result.forEach(r => {
          this.payAcctTypeData.push(r);
        })
      })
    },


    addClearPlan() {
      var record = {};
      record.instId = this.instId;
      let clearSeqTmp = 1
      if (this.dataSource.length != 0) {
        clearSeqTmp = this.dataSource[this.dataSource.length - 1].clearSeq + 1
      }
      var clearSeq = this.dataSource.length <= 0 ? 1 : clearSeqTmp;
      record.clearSeq = clearSeq
      record.id = clearSeq

      record.optFlag = 'add'
      this.clearPlanBasic.visiable = true
      this.$refs.clearPlanBasic.setClearPlanBasicValues(record);

    },

    editClearPlan(record) {
      if (this.title == '方案新增' || this.title == '方案修改') {
        record.optFlag = 'upd'
        this.clearPlanBasic.visiable = true
        this.$refs.clearPlanBasic.setClearPlanBasicValues(record);

      }
    },

    delClearPlan(record, index) {
      if (this.title == '方案新增' || this.title == '方案修改') {
        this.dataSource.splice(index, 1);
      }
    },

    handleClearPlanBasicClose() {
      this.clearPlanBasic.visiable = false
    },
    handleClearPlanBasicSuccess(data) {
      this.clearPlanBasic.visiable = false
      console.log(data)
      if ("add" == data.optFlag) {
        this.dataSource.push(data);
        if (this.paginationInfo && this.paginationInfo.pageSize) {
          this.paginationInfo.pageSize = this.paginationInfo.pageSize + 1;
        }
      } else {
        /* 通过 this.dataSource.forEach 遍历赋值后并不会通过数据双向绑定更新dataSource里的内容 */
        for (var i = 0; i < this.dataSource.length; i++) {
          if (data.clearSeq == this.dataSource[i].clearSeq) {

            this.dataSource[i].id = data.id;
            this.dataSource[i].instId = data.instId;
            this.dataSource[i].clearSeq = data.clearSeq;
            this.dataSource[i].settleFundType = data.settleFundType;
            this.dataSource[i].clearRuleId = data.clearRuleId;
            this.dataSource[i].settleRuleId = data.settleRuleId;
          }
        }
      }
    },


    reset() {
      this.loading = false
      this.isCancel = false
      this.isUpd = false
      this.isStop = false
      this.title = '方案新增'
      this.activeKey = '1'
      this.form.resetFields()
      this.dataSource = []
      this.tmpData = {}
    },
    onClose() {
      this.reset()
      this.$emit('close')
    },

    clearPlanSubmit() {
      console.log(this.tmpData.cid + '**cid')
      if (this.dataSource.length > 0) {
        let optFlag = this.optFlagTmp

        this.dataSource.forEach((data) => {
          data.instId = this.tmpData.instId
          data.clearPlanId = this.tmpData.clearPlanId
          data.planDesc = this.tmpData.planDesc
          data.auditStatus = this.tmpData.auditStatus
          data.oprId = this.tmpData.oprId
          data.oprStatus = this.tmpData.oprStatus


        })

        const params = {
          clearPlanList: this.dataSource,
          optFlag: optFlag,
          cid: this.tmpData.cid
        }
        console.log(params)
        this.$postJson('/admin/csmc/clearPlan', params).then((r) => {
          this.reset()
          this.$emit('success')
        }).catch(() => {
          this.loading = false
        })
      } else {
        this.$message.warning("请新增清分清算方案配置")
      }

    },
    handleSubmit() {
      this.form.validateFields((err, values) => {
        this.cid = this.info.id
        if (!err) {
          console.log(values.id + '   ***id***')
          this.setInfoFields()
          this.loading = true
          this.info.instId = this.instId

          if (this.title == '方案新增') {
            this.info.optFlag = 'add'
          } else if (this.title == '方案修改') {
            this.info.optFlag = 'upd'
          } else if (this.title == '方案停用') {
            this.info.optFlag = 'stop'
          } else if (this.title == '方案启用') {
            this.info.optFlag = 'use'
          } else if (this.title == '方案注销') {
            this.info.optFlag = 'cancel'
          }

          console.log(values.id + '**  **' + this.info.id)
          let param = {
            instId: this.info.instId,
            clearPlanId: this.info.clearPlanId,
          }
          this.queryParams.instId = this.info.instId
          this.queryParams.clearPlanId = this.info.clearPlanId
          console.log(this.info)
          this.$post('/admin/csmc/clearPlanMap', {
            ...this.info
          }).then((r) => {
            this.activeKey = '2'
            this.$message.success("保存成功")
            if (this.title == '方案新增') {
              param.clearPlanId = '999999'  //不存在
            }
            this.fetch(param)
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },

    setInfoFields() {
      let values = this.form.getFieldsValue(['id', 'clearPlanId', 'planMapDesc', 'instId', 'transChannelIdList', 'payChannelIdList',
        'txnNum', 'stopReason', 'cancelReason', 'csmcBizTypeList', 'reconRslt', 'payAcctType', 'otherCond1', 'otherCond2'])
      if (typeof values !== 'undefined') {
        Object.keys(values).forEach(_key => {
          this.info[_key] = values[_key]
        })
      }
    },

    setClearPlanMapFormValues({ ...info }) {

      this.tmpData.auditStatus = info.auditStatus
      this.tmpData.instId = info.instId
      this.tmpData.oprId = info.oprId
      this.tmpData.oprStatus = info.oprStatus
      this.tmpData.planDesc = info.planMapDesc
      this.tmpData.clearPlanId = info.clearPlanId
      this.tmpData.cid = info.id

      this.optFlagTmp = info.operation
      let fields = ['id', 'clearPlanId', 'planMapDesc', 'instId', 'transChannelIdList', 'payChannelIdList',
        'txnNum', 'stopReason', 'cancelReason', 'csmcBizTypeList', 'reconRslt', 'payAcctType', 'otherCond1', 'otherCond2']
      if (info.operation == 'stop') {
        this.isStop = true
        this.isUpd = true
        this.title = '方案停用'
      } else if (info.operation == 'use') {
        this.isUpd = true
        this.title = '方案启用'
      } else if (info.operation == 'cancel') {
        this.isCancel = true
        this.isUpd = true
        this.title = '方案注销'
      } else if (info.operation == 'view') {
        this.isView = true
        this.isUpd = true
        this.title = '方案详情'
      } else if (info.operation == 'upd') {
        this.title = '方案修改'
      }
      Object.keys(info).forEach((key) => {
        if (fields.indexOf(key) !== -1) {
          this.form.getFieldDecorator(key)
          let obj = {}
          obj[key] = info[key]
          this.form.setFieldsValue(obj)
        }
      })
    },

    handleTableChange(pagination, filters, sorter) {
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.defaultPageSize
      }
      // 将这三个参数赋值给Vue data，用于后续使用
      this.paginationInfo = pagination
      // 重置列过滤器规则
      this.filteredInfo = filters
      // 重置列排序规则
      this.sortedInfo = sorter

      // this.reconSceneInfo.visiable = false
      this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...this.queryParams,
        ...filters
      })
    },
    fetch(params = {}) {
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.pageSize = this.paginationInfo.pageSize
        params.pageNum = this.paginationInfo.current
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize
        params.pageNum = this.pagination.defaultCurrent
      }

      this.$get('/admin/csmc/clearPlan', {
        ...params
      }).then((r) => {
        console.log(r);
        let data = r.data
        this.loading = false
        this.dataSource = r.data.rows
        const pagination = { ...this.pagination }
        pagination.total = data.total
        this.pagination = pagination
      })

    }

  }

}
</script>




